package threading;


// 两个代码针对 同一个变量 自增5w次

class Counter{
    private int count = 0;

    // 对count++ 这个操作进行加锁！！！
    synchronized public void add() {
        count++;
    }

    public int getCount(){
        return count;
    }
}

public class ThreadDemo6 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        //  搞了个线程，这两个线程分别对count自增5w次
        Thread t1 = new Thread( () -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        } );
        Thread t2 = new Thread( () -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        } );
        t1.start();
        t2.start();

        // 等待两个线程执行完毕
        t1.join();
        t2.join();

        System.out.println(counter.getCount());
    }
}
